package com.ziyun.erp.modules.order.aspect;

import com.ziyun.erp.modules.order.annotation.OrderLog;
import com.ziyun.erp.modules.order.entity.ErpOrderLogEntity;
import com.ziyun.erp.modules.order.service.ErpOrderLogService;
import com.ziyun.erp.modules.order.service.ErpOrderService;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单操作日志切面
 * @author gaosheng
 */
@Aspect
@Component
public class OrderLogAspect {

    @Autowired
    private ErpOrderLogService erpOrderLogService;
    @Autowired
    private ErpOrderService erpOrderService;


    @Pointcut("@annotation(com.ziyun.erp.modules.order.annotation.OrderLog)")
    public void logPointCut() {}

    @AfterReturning(value = "logPointCut() && @annotation(log)",returning = "result")
    public void afterReturn(JoinPoint joinPoint, Object result, OrderLog log){
        HashMap<String, Object> resultMap = (HashMap<String, Object>) result;
        int code = (int) resultMap.get("code");
        String orderNo=null;
        String username=null;
        Long userId=null;
        if (code == 0){
            //请求的参数
            Object[] args = joinPoint.getArgs();
            if( args[0] instanceof Map){
                Map paramMap=(Map)args[0];
                paramMap.get("userName").toString();
                orderNo=((Map)args[0]).get("orderId").toString();
                userId=Long.valueOf(((Map)args[0]).get("userId").toString());
            }else{
                orderNo = (String) args[0];
                //用户名
                username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
                //用户ID
                userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
            }
            boolean isOrderNo = log.orderNo();
            if (!isOrderNo){
                orderNo = erpOrderService.selectOrderNoByOrderId(Long.valueOf(orderNo));
            }
            if (orderNo != null){
                //操作信息
                String desc = log.desc();
                ErpOrderLogEntity erpOrderLogEntity = new ErpOrderLogEntity();
                erpOrderLogEntity.setCreateBy(userId.toString());
                erpOrderLogEntity.setCreateName(username);
                erpOrderLogEntity.setCreateTime(new Date());
                erpOrderLogEntity.setOrderNo(orderNo);
                erpOrderLogEntity.setLogText(desc);
                erpOrderLogService.insert(erpOrderLogEntity);
            }
        }
    }

}
